﻿using ExitGames.Threading;
using MOBAServer.Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace MOBAServer.Cache
{
    /// <summary>
    /// 账号的缓存层
    /// </summary>
    public class AccountCache
    {
        #region 数据
        /// <summary>
        /// 账号和模型的映射
        /// </summary>
        private SynchronizedDictionary<string, AccountModel> accModelDic = new SynchronizedDictionary<string, AccountModel>();
        /// <summary>
        /// 匹配账号密码是否存在正确
        /// </summary>
        /// <returns></returns>
        public bool Match(string acc, string pwd)
        {
            if (!accModelDic.ContainsKey(acc))
            {
                return false;
            }
            return accModelDic[acc].Password == pwd;
        }
        private int id = 0;

        public bool Add(string acc, string pwd)
        {
            if (Has(acc))
            {
                return false;
            }
            accModelDic[acc] = new AccountModel(id, acc, pwd);
            id++;
            return true;
        }
        /// <summary>
        /// 是否有账号
        /// </summary>
        /// <param name="acc">账号</param>
        /// <returns></returns>
        public bool Has(string acc)
        {
            return accModelDic.ContainsKey(acc);
        }
        #endregion
        #region 在线玩家
        private SynchronizedDictionary<MobaClient, string> clientAcctDic = new SynchronizedDictionary<MobaClient, string>();
        private SynchronizedDictionary<string, MobaClient> acctClientDic = new SynchronizedDictionary<string, MobaClient>();
        public bool IsOnline(string acc)
        {
           return acctClientDic.ContainsKey(acc);
        }
        /// <summary>
        /// 添加在线关系
        /// </summary>
        /// <param name="acc"></param>
        /// <param name="client"></param>
        public bool OnLine(string acc,MobaClient client)
        {
            if(IsOnline(acc))
            {
                return false;
            }
            clientAcctDic[client] =acc;
            acctClientDic[acc] = client;
            return true;
        }
        /// <summary>
        /// 下线
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public void OffLine(MobaClient client)
        {
            if (!clientAcctDic.ContainsKey(client))
                return;
            string acc = clientAcctDic[client];
            if (acctClientDic.ContainsKey(acc))
                acctClientDic.Remove(acc);
            if(clientAcctDic.ContainsKey(client))
                clientAcctDic.Remove(client);

        }
        #endregion
        public int GetId(MobaClient client)
        {
            if (!clientAcctDic.ContainsKey(client))
                return -1;
            string account = clientAcctDic[client];
            if (!accModelDic.ContainsKey(account))
                return -1;
            return accModelDic[account].Id;
        }
    }
}
